/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.State;
import com.velocityme.entity.TaskStateMachine;
import com.velocityme.enums.ChangeDeltaItemType;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class StateBean implements StateLocal {
    @EJB
    private NodeLocal nodeBean;

    @PersistenceContext
    private EntityManager em;

    public Collection<State> findAllStates(KeyLocal key) {
        key.validateKey();
        return em.createNamedQuery("findAllStates").getResultList();
    }

    public State findState(KeyLocal key, Long stateId) {
        State state = em.find(State.class, stateId);
        key.assertHasPermission(state, Permission.NODE_VIEW);
        return state;
    }

    public State createState(KeyLocal key, State state) {
        key.assertHasPermission(state.getParentNode(), Permission.STATE_CREATE);
        ChangeDelta changeDelta = state.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        nodeBean.logCreate(state, changeDelta);
        changeDelta.addItem(ChangeDeltaItemType.ACTIVE, Boolean.toString(state.isActive()));
        em.persist(state);
        em.persist(changeDelta);
        return state;
    }

    public void editState(KeyLocal key, State state) {
        State current = em.find(State.class, state.getId());
        key.assertHasPermission(state, Permission.STATE_EDIT);
        ChangeDelta changeDelta = state.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        nodeBean.logEdit(state, current, changeDelta);
        if (state.isActive() != current.isActive()) {
            changeDelta.addItem(ChangeDeltaItemType.ACTIVE, Boolean.toString(state.isActive()));
        }
        em.persist(changeDelta);
        em.merge(state);
    }

    public State findStartState(KeyLocal key) {
        key.validateKey();
        return (State) em.createNamedQuery("findStartState").getSingleResult();
    }

    public Collection<State> findStates(KeyLocal key, TaskStateMachine taskStateMachine) {
        key.validateKey();
        return em.createNamedQuery("findTaskStateMachineStates").
                setParameter("taskStateMachine", taskStateMachine).
                getResultList();
    }



}
